/**
 * @author haoliwei
 * @date 2014-9-26
 */
package net.oscorner.commons;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;


/**
 * @author haoliwei
 * @date 2014-9-26 下午3:17:10
 * 
 */

public class BaseDao {
	private BasicDataSource dataSource = (BasicDataSource)SpringsUtils.getApplicationContext().getBean("basicDataSource");

	private QueryRunner qr = new QueryRunner(dataSource);
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List executeQuery(String sql,Object[] params,Class c) throws SQLException{
		List list = null;
		ResultSetHandler rsh = new BeanListHandler(c);
		list =  (List) qr.query(sql, rsh, params);
		return list;
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List executeQuery(String sql,Class c) throws SQLException{
		List list = null;
		//Object o = qr.query(sql, rsh);
		ResultSetHandler rsh = new BeanListHandler(c);
		list =  (List) qr.query(sql, rsh);
		return list;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object executeQueryObject(String sql,Object[] params,Class c) throws SQLException{
		Object o = null;
		ResultSetHandler rsh = new BeanHandler(c);
		o = (Object)qr.query(sql, rsh, params);
		
		return o;
	}
	
	public int executeCount(String sql,Object [] params) throws SQLException{
		Integer result ;
		result = qr.query(sql,new ResultSetHandler<Integer>() {
			@Override
			public Integer handle(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				rs.next();
				return rs.getInt(1);
			}
		},params);
		return result;
	}

	public int executeInsert(String sql,Object [] params) throws SQLException{
		int resultId = 0;
		resultId = qr.update(sql, params);
		return resultId;
	}
	public int executeUpdate(String sql,Object [] params) throws SQLException{
		int resultId = 0;
		resultId = qr.update(sql, params);
		return resultId;
	}

	public int executeDelete(String sql,Object [] params) throws SQLException{
		int resultId = 0;
		resultId = qr.update(sql, params);
		return resultId;
	}
}
